package cn.hyh;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author hyh
 * @date 2020/10/13
 */
public class FileUtil {

    /**
     * 从url下载文件
     *
     * @param url      请求路径
     * @param path     下载保存目录
     * @param filename 文件名
     * @throws IOException 访问或保存失败
     */
    public static void downloadFromUrl(String url, String path, String filename) throws IOException {
        File pathFile = new File(path);
        // 判断下载保存目录是否存在
        if (!pathFile.exists()) {
            throw new RuntimeException("下载目录不存在");
        }
        // 判断下载保存目录是否为目录类型
        if (!pathFile.isDirectory()) {
            throw new RuntimeException("下载目录需为路径");
        }
        downloadFromUrl(url, path + File.separator + filename);
    }

    /**
     * 从url下载文件
     *
     * @param url          请求路径
     * @param filePathName 文件全路径名称
     * @throws IOException 访问或保存失败
     */
    public static void downloadFromUrl(String url, String filePathName) throws IOException {
        HttpClient client = new HttpClient();
        GetMethod getMethod = new GetMethod(url);
        client.executeMethod(getMethod);
        FileOutputStream fileOutputStream = new FileOutputStream(new File(filePathName));
        fileOutputStream.write(getMethod.getResponseBody());
        fileOutputStream.close();
    }

}
